<?php
// require VENDOR_PATH.'aliyun-php/aliyun-php-sdk-core/Config.php';
// use vod\Request\V20170321 as vod;

/**
 * 返回APP接口JSON数据-----已弃用
 * @DateTime 2017-03-27T13:39:15+0800
 * @param    [number] status
 * @param    [array]  data
 * @param    [string] info
 * @return   [json]   {"status":0,"info":"成功","data":[]} 
 * 						status:0为正常状态，>0为数据异常
 * 						info:提示信息
 * 						data:返回数据
 */
function json_parse($status,$data,$info){
	$json=array();
	$json['status']=$status;
	$json['info']=$info;
	$json['data']=$data;
	header('Content-Type:application/json; charset=utf-8');
    exit(json_encode($json,JSON_UNESCAPED_UNICODE));
}

function getSex($sex){
    switch ($sex){
        case 0:
            $sex="保密";
            break;
        case 1:
            $sex="男";
            break;
        case 2:
            $sex="女";
            break;
        default:
            $sex="未知";
    }
    return $sex;
}

/**
 * 从身份证号获取性别信息
 * @param $num
 * @return string
 */
function getSexFromPeopleIdcard($idcard){
    $sex = substr($idcard, (strlen($idcard)==15 ? -2 : -1), 1) % 2 ? '1' : '2';
    return $sex;
}

/**
 * 从身份证号获取生日信息
 * @param $num
 * @return string
 */
function getBirthFromPeopleIdcard($idcard){
    $idcard=(string)$idcard;
    $birth = strlen($idcard)==15 ? ('19' . substr($idcard, 6, 6)) : substr($idcard, 6, 8);
    return date("Y-m-d",strtotime($birth));
}

/*********************************************************************************
函数功能：截取utf8或GB2312或者GBK编码的字符串，从第一个字符开始截取，1个长度代表一个汉字
$sourcestr------------截取源字符串
$cutlength------------截取长度(字数)
这个函数很万能，但是相对前两个耗资源一些
 *********************************************************************************/
function substr_for_utf8($sourcestr,$cutlength)
{
    $returnstr='';
    $i=0;
    $n=0;
    $str_length=strlen($sourcestr);	//字符串的字节数
    while (($n<$cutlength) and ($i<=$str_length))
    {
        $temp_str=substr($sourcestr,$i,1);
        $ascnum=Ord($temp_str); //得到字符串中第$i位字符的ascii码
        if ($ascnum>=224) //如果ASCII位高与224，
        {
            $returnstr=$returnstr.substr($sourcestr,$i,3); //根据UTF-8编码规范，将3个连续的字符计为单个字符
            $i=$i+3; //实际Byte计为3
            $n++; //字串长度计1
        }
        elseif ($ascnum>=192)//如果ASCII位高与192，
        {
            $returnstr=$returnstr.substr($sourcestr,$i,2); //根据UTF-8编码规范，将2个连续的字符计为单个字符
            $i=$i+2; //实际Byte计为2
            $n++; //字串长度计1
        }
        elseif ($ascnum>=65 && $ascnum<=90) //如果是大写字母，
        {
            $returnstr=$returnstr.substr($sourcestr,$i,1);
            $i=$i+1; //实际的Byte数仍计1个
            $n++; //但考虑整体美观，大写字母计成一个高位字符
        }
        else //其他情况下，包括小写字母和半角标点符号，
        {
            $returnstr=$returnstr.substr($sourcestr,$i,1);
            $i=$i+1;	//实际的Byte数计1个
            $n=$n+0.5;	//小写字母和半角标点等与半个高位字符宽...
        }
    }
    if ($str_length>$cutlength && $returnstr!=$sourcestr)
    {
        $returnstr = $returnstr . "...";	//超过长度时在尾处加上省略号
    }
    return $returnstr;
}

/**
 * 从字符串内删除自定字符后返回剩余值
 * @param $str 原字符
 * @param $delete 待删除字符串
 * @return mixed 剩余字符串
 */
function delStr($str,$delete)
{
    $count=strpos($str,$delete);
    return substr_replace($str,"",$count,strlen($delete));
}

/**
 * 获取用户头像真实地址
 */
function get_user_avatar($avatar){

    if($avatar){
        if(strpos($avatar, "http")===0){
            return $avatar;
        }else {
            $url =  sp_get_asset_upload_path($avatar,false);
            if(C('FILE_UPLOAD_TYPE')=='Qiniu'){
                $storage_setting=sp_get_cmf_settings('storage');
                $qiniu_setting=$storage_setting['Qiniu']['setting'];
                $filepath=$qiniu_setting['protocol'].'://'.$storage_setting['Qiniu']['domain']."/".$avatar;
                if($qiniu_setting['enable_picture_protect']){
                    $url = $url.$qiniu_setting['style_separator'].$qiniu_setting['styles']['avatar'];
                }
            }

            return $url;
        }

    }else{
        return $avatar;
    }

}

/**
 * 获取BBS图片地址
 */
function get_bbs_image($image,$folder="bbs"){
    
    $folder.="/";
    if($image){
        if(strpos($image, "http")===0){
            return $image;
        }else {
            if(strpos($image, $folder)===false){
                $image=$folder.$image;
            }
            $url =  sp_get_asset_upload_path($image,false);

            return $url;
        }

    }else{
        return $image;
    }

}

function get_bbs_image_small($url){

    $link=explode(".",$url);
    $ext=array_pop($link);
    $ext="_small.$ext";
    return $url.$ext;
}

/**
 * 添加积分具体执行函数
 * @param $userId 用户ID
 * @param $coin  积分数
 * @param $content 添加积分理由
 *
 */
function _addMyCoin($userId,$coin,$content){
    if (!($coin>0 && $content!="")){
        return [6,array(),"参数错误，积分更新失败"];
    }

    $Model = M(); // 实例化一个空对象
    $Model->startTrans(); // 开启事务

    $return=$Model->table("__USERS__")->where(array('id'=>$userId))->setInc('coin',$coin);
    $user=$Model->table("__USERS__")->field("company,coin")->find($userId);
    if ($return!==false) {
        /**
         * 存储积分增加历史记录
         */
        $data=array();
        $data['user_id']=$userId;
        $data['num']=$coin;
        $data['content']=$content;
        $data['year']=date('Y');
        $data['month']=date('n');
        $data['create_time']=date('Y-m-d H:i:s');
        $result=$Model->table("__USERS_COIN_HISTORY__")->add($data);
        if ($return!==false) {
            $return=$Model->table("__COMPANY__")->where(array('id'=>$user['company']))->setInc('coins',$coin);
            if ($return!==false){
                $Model->commit(); // 成功则提交事务
                return array(0, array("coin" => $user['coin']), "成功");
            }else{
                $returnArray = array(4,array(),M("Company")->getError());
            }
        }else{
            $returnArray = array(3,array(),$this->coin_model->getError());
        }
    }else{
        $returnArray = array(2,array(),$this->users_model->getError());
    }
    $Model->rollback(); // 否则将事务回滚

    $log="用户积分获取失败:用户ID：$userId;积分数量：$coin;积分内容:$content";
    \Think\Log::record($log,'ALERT');

    return $returnArray;
}

/**
 * 验证手机号是否正确
 * @author honfei
 * @param number $mobile
 */
function isMobile($mobile) {
    if (!is_numeric($mobile)) {
        return false;
    }
    return preg_match('/^1[34578]{1}\d{9}$/', $mobile) ? true : false;
}

function randomKeys($length)
{
    $output='';
    for ($a = 0; $a < $length; $a++) {
        $output .= chr(mt_rand(48, 57));    //生成php随机数
    }
    return $output;
}

/**
 * 旧短信接口 慢
 * @DateTime 2017-06-15T14:31:36+0800
 * @param    [type]                   $Mobile  [description]
 * @param    [type]                   $Content [description]
 */
function NewSms($Mobile,$Content){
    $url="http://service.winic.org:8009/sys_port/gateway/index.asp?";
    $data = "id=%s&pwd=%s&to=%s&content=%s&time=";
    $id = 'eightmouths';
    $pwd = 'letsface';
    $to = $Mobile;
    $content = iconv("UTF-8","GB2312",$Content);
    $rdata = sprintf($data, $id, $pwd, $to, $content);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST,1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$rdata);
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

/**
 * 新短信接口 快
 * @DateTime 2017-06-15T14:32:08+0800
 * @param    [type]                   $Mobile  [description]
 * @param    [type]                   $Content [description]
 * @return   [type]                            [description]
 */
function kxtSms($Mobile,$Content){
    $url="http://114.215.196.145/sendSmsApi?";
    $data = "username=%s&password=%s&mobile=%s&content=%s";
    $username = 'zxxkj';
    $pwd = 'xonYx114';
    $rdata = sprintf($data, $username, $pwd, $Mobile, $Content);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST,1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$rdata);
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    $result = curl_exec($ch);
    curl_close($ch);
    //dump($result);//exit;
    return $result;
}

function addContentUrl($content){
    $piece="<img src=\"";
    $list=explode($piece, $content);
    $piece.="http://".$_SERVER['HTTP_HOST'];
    $content=implode($list, $piece);
    return $content;
}

function initAliyun(){
    $data=[];
    $data['regionId'] = 'cn-shanghai';
    $data['profile'] = \DefaultProfile::getProfile($data['regionId'], "LTAIM0ZQJNrVe5f3", "7KXO5g0CDVNbcGLruUMgL7CVeOSXQ0");
    $data['client']= new \DefaultAcsClient($data['profile']);

    return $data;
}

function aliyun_refresh_upload_video($videoId) {
    $ali=initAliyun();
    $request = new vod\RefreshUploadVideoRequest();
    $request->setAcceptFormat('JSON');
    $request->setRegionId($ali['regionId']);
    $request->setVideoId($videoId);
    $response = $ali['client']->getAcsResponse($request);

    return $response;
}

function ali_create_upload_video($title,$content,$filename,$fileSize,$cateId=424682) {

    $ali=initAliyun();

    $request = new vod\CreateUploadVideoRequest();
    $request->setAcceptFormat('JSON');
    $request->setRegionId($ali['regionId']);
    $request->setTitle($title);
    //视频源文件名称(必须包含扩展名)
    $request->setFileName($filename);
    //视频源文件字节数
    $request->setFileSize($fileSize);
    $request->setDescription($content);
    //自定义视频封面URL地址
    //$request->setCoverURL("http://cover.sample.com/sample.jpg");
    //上传所在区域IP地址
    $request->setIP("127.0.0.1");
    //$request->setTags("标签1,标签2");
    //视频分类ID
    $request->setCateId($cateId);
    $response = $ali['client']->getAcsResponse($request);
    //dump($response);
    return $response;
}

function  ali_get_video_playauth($videoId) {
    $ali=initAliyun();

    $request = new vod\GetVideoPlayAuthRequest();
    $request->setAcceptFormat('JSON');
    $request->setRegionId($ali['regionId']);
    $request->setVideoId($videoId);            //视频ID
    $response = $ali['client']->getAcsResponse($request);
    return $response;
}

function  ali_get_video_info($videoId) {
    $ali=initAliyun();

    $request = new vod\GetVideoInfoRequest();
    $request->setAcceptFormat('JSON');
    $request->setRegionId($ali['regionId']);
    $request->setVideoId($videoId);            //视频ID
    $response = $ali['client']->getAcsResponse($request);
    return $response;
}

//PHP stdClass Object转array
function object_array($array) {
    if(is_object($array)) {
        $array = (array)$array;
    } if(is_array($array)) {
        foreach($array as $key=>$value) {
            $array[$key] = object_array($value);
        }
    }
    return $array;
}

function current_datetime() {
    return date('Y-m-d H:i:s');
}

function checkBadgeRule($userId,$badgeIds) {
    $Model=D("Badge");
    $badgeIds=getSpecialBadgeIDS($badgeIds);
    //dump($badgeIds);exit;
    $data=$Model->checkBadge($userId,$badgeIds);

    return $data;
}

function getSpecialBadgeIDS($badgeIds) {
    $badgeIds=explode(",",$badgeIds);
    $array=[
        1=>25,
        2=>25,
        3=>25,
        4=>25,
        5=>25,
        6=>25,
        7=>26,
        8=>26,
        9=>26,
        10=>26,
        11=>26,
        12=>26,
        13=>26,
        14=>27,
        15=>27,
        16=>27,
        17=>27,
        18=>27,
        19=>27,
        20=>27,
        21=>28,
        22=>28,
        23=>28,
        24=>28
    ];
    $ids=[];
    foreach ($badgeIds as $id){
        $id=$array[$id];
        $badgeIds[$id]=$id;
    }
    $badgeIds=implode(",",$badgeIds);

    return $badgeIds;
}

function analysisImages($images){
    //dump($images);
    $images=explode("|",$images);
    //dump($images);
    $return=[];
    if(isset($images[0]) && !empty($images[0])) {
        foreach ($images as $k => $v) {
            if(empty($v)){continue;}
            $v = explode(",", $v);
            //dump($v);
            $return[] = [
                "id" => $v[0],
                "image" => get_bbs_image($v[1],'file')
            ];
        }
    }
    return $return;
}

function analysisImages2($images){
    $images=json_decode($images,true);
    //dump($images);exit;

    $return=[];
    if(isset($images[0]) && !empty($images[0])) {
        foreach ($images as $v) {
            $return[] = get_bbs_image($v,'file');
        }
    }
    return $return;
}

/**
 * 获取需求订单信息
 * @param $sn string 订单sn
 * @return bool|mixed
 */
function get_require_order_by_sn($sn){
    $where['o.sn']=$sn;
    $order=M("Require_order")
            ->alias("o")
            ->join("__REQUIRE_ANS__ a ON a.id=o.ans_id")
            ->join("__REQUIRE__ r ON r.id=a.require_id")
            ->where($where)
            ->field("o.*,r.user_id,a.user_id as business_id,a.user_type")
            ->find();
    if(!$order){
        return false;
    }
    return $order;
}

/**
 * 获取扫一扫支付订单信息
 * @param $sn string 订单sn
 * @return bool|mixed
 */
function get_scan_pay_by_sn($sn){
    $where['sn']=$sn;
    $order=M("ScanPay")
            ->where($where)
            ->field("*")
            ->find();
    $order["category"]=2;
    if(!$order){
        return false;
    }
    return $order;
}

function get_host_name(){
    return "http://".$_SERVER['HTTP_HOST'];
}